import { ModalForm, ProForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormTimePicker } from '@ant-design/pro-components';
import type { Meeting } from '@fill/client';
import { queryClient, rspc } from '@fill/client';
import { Button, Form } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { STATUS_VALUE } from '../../constants/default';
import type { IUploadFile } from '../../util';
import { UploadFile } from '../report/Upload';

export const MeetingUpdate = (records: Meeting) => {
  const meetingSave = rspc.useMutation('meetings.save');
  const [form] = Form.useForm<any>();
  const [open, setOpen] = useState(false);

  const [attachment, setAttachment] = useState<IUploadFile[]>([]);

  useEffect(() => {
    setAttachment(JSON.parse(records?.attachment || '[]'));
  }, [records]);

  useEffect(() => {
    if (!open)
      return;
    form.setFieldsValue({
      ...records,
      members: records.members.split(','),
      time: records.time.split(','),
      outline: records.outline?.replaceAll('<br />', '\n'),
    });
  }, [open]);

  async function handleSubmit(tmp = false) {
    try {
      await form.validateFields();
    }
    catch (error) {
      return;
    }

    const values = form.getFieldsValue();
    console.log(values);
    await meetingSave.mutateAsync({
      arg: {
        ...records,
        ...values,
        members: (values.members as unknown as string[]).join(),
        started_at: dayjs(values.started_at).format('YYYY-MM-DD HH:mm:ss'),
        time: (values.time as unknown as string[]).filter(item => !!item).join(),
        attachment: JSON.stringify(values.attachment),
        status: tmp ? STATUS_VALUE.PENDING : STATUS_VALUE.PROCESSED,
      },
    }, {
      onSuccess() {
        queryClient.refetchQueries({
          queryKey: ['meetings.get'],
        });
      },
    });

    setOpen(false);
  }

  return (
    <>
      <a key="link" onClick={() => setOpen(true)}>编辑</a>
      <ModalForm<Meeting>
        width={1000}
        title="编辑研究整改工作"
        // trigger={
        //   <a key="link">编辑</a>
        // }
        layout="horizontal"
        modalProps={{
          destroyOnClose: true,
          onCancel: () => console.log('run'),
        }}
        grid
        form={form}
        open={open}
        labelCol={{ span: 4 }}
        rowProps={{
          gutter: [6, 6],
        }}
        // initialValues={{
        //   ...records,
        //   members: records.members.split(','),
        //   time: records.time.split(','),
        //   outline: records.outline?.replaceAll('<br />', '\n'),
        // }}
        onOpenChange={(e) => {
          setOpen(e);
        }}
        submitter={{
          render() {
            return <div style={{
              display: 'flex',
              flex: 1,
              justifyContent: 'center',
            }}>
              {[
                <Button type="primary" key="tmp" onClick={() => handleSubmit(true)}>暂存</Button>,
                <Button type="primary" key="submit" onClick={() => handleSubmit()}>确定</Button>,
                <Button key="cancel" onClick={() => setOpen(false)}>取消</Button>,
              ]}
            </div>;
          },
        }}
        // onFinish={async (values) => {
        //   console.log({
        //     ...records,
        //     ...values,
        //     members: (values.members as unknown as string[]).join(),
        //     started_at: dayjs(values.started_at).format('YYYY-MM-DD HH:mm:ss'),
        //     time: (values.time as unknown as string[]).join(),
        //     attachment: JSON.stringify(values),
        //   });

        //   try {
        //     await meetingSave.mutateAsync({
        //       arg: {
        //         ...records,
        //         ...values,
        //         members: (values.members as unknown as string[]).join(),
        //         started_at: dayjs(values.started_at).format('YYYY-MM-DD HH:mm:ss'),
        //         time: (values.time as unknown as string[]).join(),
        //         attachment: JSON.stringify(values.attachment),
        //         status: STATUS_VALUE.PROCESSED,
        //       },
        //     }, {
        //       onSuccess() {
        //         queryClient.refetchQueries({
        //           queryKey: ['meetings.get'],
        //         });
        //       },
        //     });

        //     return true;
        //   }
        //   catch (error) {
        //     return false;
        //   }
        // }}
      >
        <div style={{
          padding: 10,
        }}></div>
        <ProFormText
          name="slug"
          label="会议主题"
          placeholder="请输入会议主题"
          colProps={{
            md: 24,
          }}
          rules={[
            {
              required: true,
              message: '请输入会议主题',
            },
          ]}
        />
        <ProFormDatePicker
          name="started_at"
          label="会议日期"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 8,
          }}
          width="md"
          rules={[
            {
              required: true,
              message: '请选择会议日期',
            },
          ]}
        />
        <ProFormTimePicker.RangePicker
          name="time"
          label="会议时间"
          dataFormat="HH:mm"
          fieldProps={{
            format: 'HH:mm',
          }}
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 6,
          }}
          width="md"
          rules={[
            {
              required: true,
              message: '请选择会议时间',
            },
          ]}
        />
        <ProFormText
          name="presenter"
          label="主持人"
          placeholder="请输入主持人"
          rules={[
            {
              required: true,
              message: '请输入主持人',
            },
          ]}
          width="md"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 8,
          }}
        />
        <ProFormSelect
          name="types"
          label="会议类型"
          rules={[
            {
              required: true,
              message: '请选择会议类型',
            },
          ]}
          valueEnum={{
            1: {
              text: '民主生活会',
            },
            2: {
              text: '党委会议',
            },
          }}
          width="md"
          colProps={{
            md: 12,
          }}
          labelCol={{
            span: 6,
          }}
        />
        <ProFormSelect label="参会人" rules={[
          {
            required: true,
            message: '请输入参会人',
          },
        ]} name="members" fieldProps={{
          mode: 'tags',
        }} placeholder={'请输入参会人'} />
        <ProFormTextArea label="会议提纲" name="outline" />
        <ProForm.Item style={{
          width: '100%',
        }} labelCol={{
          span: 4,
        }} name="attachment" label="会议材料" extra="支持 doc、docx、pdf、xls、xlsx、jpg 、png、jpeg、txt、ext文件格式，最大不超过200M">
          <UploadFile files={attachment} onChange={(files) => { form.setFieldValue('attachment', files); }} />
        </ProForm.Item>
      </ModalForm>
    </>
  );
};
